Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

181
Visualizações
JavaScript React setInterval "this" issue

I'm trying to learn React and I don't understand why this does not do anything when I try without an arrow function

componentDidMount() {
    var self = this
    this.timer = window.setInterval(function () {
        self.increment
    }, 1000)
}

Is the correct pattern self.increment()?

So why do I need the () when I don't need it in:

componentDidMount() {
    this.timer = window.setInterval(this.increment.bind(this),1000)
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are not invoking self.increment, you are properly scoping this for your code to work. Maybe it appears it's not working because your interval's callback does not do anything :)

Also, here's a simpler version of your code, you could omit the .bind if your function does not need to access your component's scope, but typically in react you'd want access to that:

this.timer = setInterval(this.increment.bind(this), 1000)
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda